<template>
  <div class="second-level-department-list">
    <!-- 标题和顶部按钮 -->
    <div style="margin-bottom: 15px;">
      <el-breadcrumb separator="/" style="margin-bottom: 10px;">
        <el-breadcrumb-item>
          <router-link to="/FirstLevelDepartmentList">一级科室管理</router-link>
        </el-breadcrumb-item>
        <el-breadcrumb-item>{{ parentDepartmentName || '二级科室列表' }}</el-breadcrumb-item>
      </el-breadcrumb>
      
      <span style="font-size: 25px; font-weight: bold;">
        {{ parentDepartmentName }} - 二级科室管理
      </span>
      <span style="float: right;">
        <el-button type="primary" @click="refreshList">刷新</el-button>
        <el-button type="success" @click="handleAddDepartment">新增二级科室</el-button>
        <el-button 
          type="danger" 
          :disabled="selectedDepartments.length === 0 || deleteLoading" 
          :loading="deleteLoading"
          @click="handleBatchDelete"
        >
          {{ deleteLoading ? '删除中...' : `批量删除 (${selectedDepartments.length})` }}
        </el-button>
        <el-button type="info" @click="goBack">返回上级</el-button>
      </span>
    </div>
    
    <!-- 搜索区域 -->
    <el-card class="box-card" shadow="hover" style="margin-bottom: 20px;">
      <template #header>
        <div class="card-header">
          <span>搜索条件</span>
        </div>
      </template>
      <div class="search-bar">
        <el-input 
          v-model="searchForm.DepartmentName" 
          placeholder="请输入科室名称" 
          style="width: 200px; margin-right: 10px;" 
          clearable
        />
        <el-select
          v-model="searchForm.Type"
          placeholder="请选择科室类型"
          style="width: 200px; margin-right: 10px;"
          clearable
        >
          <el-option label="门诊" value="门诊" />
          <el-option label="急诊科" value="急诊科" />
          <el-option label="其他" value="其他" />
        </el-select>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button type="warning" @click="resetSearch">重置</el-button>
      </div>
    </el-card>
    
    <!-- 数据表格 -->
    <el-card class="box-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div>
            <span style="margin-left: 10px;">科室信息（共{{ pagination.totalCount }}条）</span>
          </div>
        </div>
      </template>
      
      <div v-loading="loading" element-loading-text="正在加载科室数据...">
        <el-table 
          :data="departmentList" 
          style="width: 100%"
          @selection-change="handleSelectionChange"
          stripe
          border
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="序号" width="60" />
          <el-table-column prop="departmentName" label="科室名称" min-width="120" />
          <el-table-column prop="type" label="科室类型" width="100" />
          <el-table-column prop="level" label="科室级别" width="100" />
          <el-table-column prop="parentDepartmentName" label="上级科室" min-width="120" />
          <el-table-column prop="departmentAddr" label="科室地址" min-width="150" show-overflow-tooltip />
          
          <el-table-column label="在线服务" width="60" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.isOnline ? 'success' : 'info'" size="small">
                {{ scope.row.isOnline ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="急诊服务" width="60" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.isEmergencyService ? 'success' : 'info'" size="small">
                {{ scope.row.isEmergencyService ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column prop="createPeople" label="创建人" width="100" />
          <el-table-column label="创建时间" width="160">
            <template #default="scope">
              {{ formatDateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          
          <el-table-column prop="remark" label="备注" min-width="120" show-overflow-tooltip />
          
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button 
                size="small" 
                type="warning" 
                @click="handleEditDepartment(scope.row)"
              >
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                :disabled="deleteLoading"
                @click="handleSingleDelete(scope.row)"
              >
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <!-- 分页 -->
      <el-pagination
        v-if="pagination.totalCount > 0"
        :current-page="pagination.currentPage"
        :page-size="pagination.pageSize"
        :total="pagination.totalCount"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50, 100]"
        style="margin-top: 20px; text-align: right;"
      />
    </el-card>

    <!-- 新增科室对话框 -->
    <el-dialog 
      v-model="addDialogVisible" 
      title="新增二级科室" 
      width="600px" 
      :before-close="handleCloseAddDialog"
    >
      <el-form
        :model="addForm"
        :rules="addRules"
        ref="addFormRef"
        label-width="120px"
        label-position="left"
      >
        <el-form-item label="科室名称" prop="departmentName">
          <el-input 
            v-model="addForm.departmentName" 
            placeholder="请输入科室名称"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="科室类型" prop="type">
          <el-select v-model="addForm.type" placeholder="请选择科室类型" style="width: 100%">
            <el-option label="门诊" value="门诊" />
            <el-option label="急诊" value="急诊" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="上级科室">
          <el-input :value="parentDepartmentName" disabled />
        </el-form-item>
        
        <el-form-item label="科室地址" prop="departmentAddr">
          <el-input 
            v-model="addForm.departmentAddr" 
            placeholder="请输入科室地址"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="在线服务">
          <el-switch v-model="addForm.isOnline" />
        </el-form-item>
        
        <el-form-item label="急诊服务">
          <el-switch v-model="addForm.isEmergencyService" />
        </el-form-item>
        
        <el-form-item label="备注">
          <el-input 
            v-model="addForm.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseAddDialog">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleSubmitAdd"
            :loading="addLoading"
          >
            {{ addLoading ? '创建中...' : '确定创建' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑科室对话框 -->
    <el-dialog 
      v-model="editDialogVisible" 
      title="编辑科室信息" 
      width="600px" 
      :before-close="handleCloseEditDialog"
    >
      <el-form
        :model="editForm"
        :rules="editRules"
        ref="editFormRef"
        label-width="120px"
        label-position="left"
      >
        <el-form-item label="科室名称" prop="departmentName">
          <el-input 
            v-model="editForm.departmentName" 
            placeholder="请输入科室名称"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="科室类型" prop="type">
          <el-select v-model="editForm.type" placeholder="请选择科室类型" style="width: 100%">
            <el-option label="门诊" value="门诊" />
            <el-option label="急诊科" value="急诊科" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="上级科室">
          <el-input :value="parentDepartmentName" disabled />
        </el-form-item>
        
        <el-form-item label="科室地址" prop="departmentAddr">
          <el-input 
            v-model="editForm.departmentAddr" 
            placeholder="请输入科室地址"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="在线服务">
          <el-switch v-model="editForm.isOnline" />
        </el-form-item>
        
        <el-form-item label="急诊服务">
          <el-switch v-model="editForm.isEmergencyService" />
        </el-form-item>
        
        <el-form-item label="备注">
          <el-input 
            v-model="editForm.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCloseEditDialog">取消</el-button>
          <el-button 
            type="primary" 
            @click="handleSubmitEdit"
            :loading="editLoading"
          >
            {{ editLoading ? '保存中...' : '确定保存' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getSecondLevelDepartments } from '@/http/axiosRead'
import { addSecondLevelDepartment, updateDepartment, deleteDepartments } from '@/http/axiosWrtie'
import type { Department, AddDepartmentForm, UpdateDepartmentForm } from '@/types/department'
import { 
  Edit, Delete 
} from '@element-plus/icons-vue'

// 路由相关
const route = useRoute()
const router = useRouter()

// 获取路由参数
const parentId = ref<number>(Number(route.params.parentId))
const parentDepartmentName = ref<string>(route.query.parentName as string || '')

// 响应式数据
const loading = ref(false)
const deleteLoading = ref(false)
const addLoading = ref(false)
const editLoading = ref(false)
const departmentList = ref<Department[]>([])
const selectedDepartmentIds = ref<number[]>([])
const selectedDepartments = computed(() => 
  departmentList.value.filter(dept => selectedDepartmentIds.value.includes(dept.id))
)

// 搜索表单
const searchForm = reactive({
  DepartmentName: '',
  Type: ''
})

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  totalCount: 0,
  totalPage: 0
})

// 对话框状态
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)

// 表单引用
const addFormRef = ref()
const editFormRef = ref()

// 新增表单
const addForm = reactive<AddDepartmentForm>({
  departmentName: '',
  type: '',
  paretId: parentId.value, // 设置父科室ID
  departmentAddr: '',
  isEmergencyService: false,
  isOnline: false,
  remark: '',
  createPeople: ''
})

// 编辑表单
const editForm = reactive<UpdateDepartmentForm>({
  id: 0,
  departmentName: '',
  type: '',
  paretId: parentId.value,
  departmentAddr: '',
  isEmergencyService: false,
  isOnline: false,
  remark: '',
  updatePeople: ''
})

// 表单验证规则
const addRules = reactive({
  departmentName: [
    { required: true, message: '请输入科室名称', trigger: 'blur' },
    { min: 2, max: 50, message: '科室名称长度在2到50个字符之间', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择科室类型', trigger: 'change' }
  ],
  departmentAddr: [
    { required: true, message: '请输入科室地址', trigger: 'blur' }
  ]
})

const editRules = reactive({
  departmentName: [
    { required: true, message: '请输入科室名称', trigger: 'blur' },
    { min: 2, max: 50, message: '科室名称长度在2到50个字符之间', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择科室类型', trigger: 'change' }
  ],
  departmentAddr: [
    { required: true, message: '请输入科室地址', trigger: 'blur' }
  ]
})

// 获取科室列表
const fetchDepartments = async () => {
  loading.value = true
  try {
    const params = {
      parentId: parentId.value,
      DepartmentName: searchForm.DepartmentName || undefined,
      Type: searchForm.Type || undefined
    }
    
    const res = await getSecondLevelDepartments(params)
    if (res.data.code === 200) {
      departmentList.value = res.data.pageData || []
      pagination.totalCount = res.data.totaCount || 0
      pagination.totalPage = res.data.totaPage || 0
      
      ElMessage.success(`成功加载${departmentList.value.length}条科室数据`)
    } else {
      ElMessage.error(res.data.msg || '获取科室列表失败')
      departmentList.value = []
    }
  } catch (error) {
    console.error('获取科室列表失败:', error)
    ElMessage.error('网络错误，请稍后重试')
    departmentList.value = []
  } finally {
    loading.value = false
  }
}

// 搜索功能
const handleSearch = () => {
  pagination.currentPage = 1
  fetchDepartments()
}

// 重置搜索
const resetSearch = () => {
  searchForm.DepartmentName = ''
  searchForm.Type = ''
  pagination.currentPage = 1
  fetchDepartments()
}

// 刷新列表
const refreshList = () => {
  fetchDepartments()
}

// 返回上级
const goBack = () => {
  router.push('/FirstLevelDepartmentList')
}

// 选择变化处理
const handleSelectionChange = (selection: Department[]) => {
  selectedDepartmentIds.value = selection.map(dept => dept.id)
}

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm(
    `您选择了 ${selectedDepartments.value.length} 个科室，确定要删除吗？删除后无法恢复！`,
    '批量删除确认',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    await performDelete(selectedDepartmentIds.value)
  }).catch(() => {
    ElMessage.info('已取消删除操作')
  })
}

// 单个删除
const handleSingleDelete = (department: Department) => {
  ElMessageBox.confirm(
    `确定要删除科室 "${department.departmentName}" 吗？删除后无法恢复！`,
    '删除确认',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    await performDelete([department.id])
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 执行删除操作
const performDelete = async (ids: number[]) => {
  deleteLoading.value = true
  try {
    // 获取当前登录用户信息
    const updatePeople = localStorage.getItem('name') || localStorage.getItem('userName') || 'admin'
    
    const response = await deleteDepartments({
      ids: ids,
      updatePeople: updatePeople
    })
    
    if (response.data && response.data.message) {
      // 显示详细的删除结果
      const { message, successCount, failCount, failedIds } = response.data
      
      // 如果有成功删除的记录
      if (successCount > 0) {
        ElMessage.success(message)
      }
      
      // 如果有失败的记录，显示具体的失败信息
      if (failCount > 0) {
        if (failCount === ids.length) {
          // 全部失败，显示错误信息
          ElMessage.error(message)
        } else {
          // 部分失败，显示警告信息  
          ElMessage.warning(message)
        }
      }
      
      // 清空选中状态
      selectedDepartmentIds.value = []
      // 刷新科室列表
      fetchDepartments()
    } else {
      ElMessage.error('删除失败，请重试')
    }
  } catch (error: any) {
    console.error('删除科室失败:', error)
    
    // 尝试从错误响应中获取业务信息
    if (error.response && error.response.data && error.response.data.message) {
      const { message, successCount, failCount } = error.response.data
      
      if (successCount > 0) {
        ElMessage.success(`成功删除 ${successCount} 个科室`)
      }
      
      if (failCount > 0) {
        ElMessage.error(message)
      }
      
      // 清空选中状态并刷新列表
      selectedDepartmentIds.value = []
      fetchDepartments()
    } else {
      ElMessage.error('删除操作失败，请重试')
    }
  } finally {
    deleteLoading.value = false
  }
}

// 分页处理
const handlePageChange = (page: number) => {
  pagination.currentPage = page
  fetchDepartments()
}

const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  fetchDepartments()
}

// 新增科室
const handleAddDepartment = () => {
  resetAddForm()
  addDialogVisible.value = true
}

// 重置新增表单
const resetAddForm = () => {
  Object.assign(addForm, {
    departmentName: '',
    type: '',
    paretId: parentId.value,
    departmentAddr: '',
    isEmergencyService: false,
    isOnline: false,
    remark: '',
    createPeople: ''
  })
  addFormRef.value?.clearValidate()
}

// 关闭新增对话框
const handleCloseAddDialog = () => {
  addDialogVisible.value = false
  resetAddForm()
}

// 提交新增
const handleSubmitAdd = async () => {
  if (!addFormRef.value) return
  
  try {
    const valid = await addFormRef.value.validate()
    if (!valid) return
    
    addLoading.value = true
    
    // 获取当前登录用户信息
    const createPeople = localStorage.getItem('name') || localStorage.getItem('userName') || 'admin'
    addForm.createPeople = createPeople
    
    const response = await addSecondLevelDepartment(parentId.value, addForm)
    
    if (response.data && response.data.id) {
      ElMessage.success(response.data.message || '科室创建成功')
      addDialogVisible.value = false
      resetAddForm()
      fetchDepartments()
    } else {
      ElMessage.error('科室创建失败')
    }
  } catch (error) {
    console.error('创建科室失败:', error)
    ElMessage.error('创建科室失败，请重试')
  } finally {
    addLoading.value = false
  }
}

// 编辑科室
const handleEditDepartment = (department: Department) => {
  Object.assign(editForm, {
    id: department.id,
    departmentName: department.departmentName,
    type: department.type,
    paretId: department.paretId,
    departmentAddr: department.departmentAddr,
    isEmergencyService: department.isEmergencyService,
    isOnline: department.isOnline,
    remark: department.remark,
    updatePeople: ''
  })
  editDialogVisible.value = true
}

// 关闭编辑对话框
const handleCloseEditDialog = () => {
  editDialogVisible.value = false
  editFormRef.value?.clearValidate()
}

// 提交编辑
const handleSubmitEdit = async () => {
  if (!editFormRef.value) return
  
  try {
    const valid = await editFormRef.value.validate()
    if (!valid) return
    
    editLoading.value = true
    
    // 获取当前登录用户信息
    const updatePeople = localStorage.getItem('name') || localStorage.getItem('userName') || 'admin'
    editForm.updatePeople = updatePeople
    
    const response = await updateDepartment(editForm)
    
    if (response.data && response.data.message) {
      ElMessage.success(response.data.message)
      editDialogVisible.value = false
      fetchDepartments()
    } else {
      ElMessage.error('科室信息更新失败')
    }
  } catch (error) {
    console.error('更新科室失败:', error)
    ElMessage.error('更新科室失败，请重试')
  } finally {
    editLoading.value = false
  }
}

// 格式化时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  // 验证路由参数
  if (!parentId.value || isNaN(parentId.value)) {
    ElMessage.error('无效的父科室ID')
    router.push('/FirstLevelDepartmentList')
    return
  }
  
  fetchDepartments()
})
</script>

<style scoped>
.second-level-department-list {
  padding: 24px;
  background: #f5f7fa;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 10px;
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  font-weight: bold;
  font-size: 16px;
}

.dialog-footer {
  text-align: right;
}

.dialog-footer .el-button {
  margin-left: 10px;
}

/* 表单布局优化 */
.el-form .el-form-item {
  margin-bottom: 18px;
}

/* 面包屑导航样式 */
:deep(.el-breadcrumb__item:last-child .el-breadcrumb__inner) {
  color: #303133;
  font-weight: normal;
}

:deep(.el-breadcrumb__item:last-child .el-breadcrumb__inner:hover) {
  color: #303133;
  cursor: default;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-bar > * {
    width: 100% !important;
    margin-right: 0 !important;
    margin-bottom: 10px;
  }
  
  .search-bar .el-button {
    margin-bottom: 5px;
  }
}
</style>